/*
 * Copyright © 2008 PCCW Solutions All right reserved.
 *
 */
package com.blues.framework.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.BasicRowProcessor;

/**
 * 实现数据库查询分页结果到实体的映射
 * @author: Kyle.Zhang
 */ 
public abstract class PageObjectListHandler implements ResultSetHandler, IQueryRecordCount {
	boolean needQueryCount = false; // 是否需要设置查询参数
	boolean returnByOutParameter = false; // 使用输出参数返回记录数，否则查询记录总数在结果列 COUNT_BY_OVER_
	long queryRecordCount = 0; // 记录总数

	protected PageObjectListHandler(boolean needQueryCount) {
		this.needQueryCount = needQueryCount;
		this.returnByOutParameter = true;
	}

	protected PageObjectListHandler(boolean needQueryCount, boolean returnByOutParameter) {
		this.needQueryCount = needQueryCount;
		this.returnByOutParameter = returnByOutParameter;
	}

	/* (non-Javadoc)
     * @see com.pccw.eHR.workflow.database.IQueryRecordCount#isNeedQueryCount()
     */
	public boolean isNeedQueryCount() {
		return needQueryCount;
	}

	/* (non-Javadoc)
     * @see com.pccw.eHR.workflow.database.IQueryRecordCount#setNeedQueryCount(boolean)
     */
	public void setNeedQueryCount(boolean needQueryCount) {
		this.needQueryCount = needQueryCount;
	}

	/* (non-Javadoc)
     * @see com.pccw.eHR.workflow.database.IQueryRecordCount#isReturnByOutParameter()
     */
	public boolean isReturnByOutParameter() {
		return returnByOutParameter;
	}

	/* (non-Javadoc)
     * @see com.pccw.eHR.workflow.database.IQueryRecordCount#setReturnByOutParameter(boolean)
     */
	public void setReturnByOutParameter(boolean returnByOutParameter) {
		this.returnByOutParameter = returnByOutParameter;
	}

	/* (non-Javadoc)
     * @see com.pccw.eHR.workflow.database.IQueryRecordCount#getQueryRecordCount()
     */
	public long getQueryRecordCount() {
		return queryRecordCount;
	}
	
	/* (non-Javadoc)
     * @see com.pccw.eHR.workflow.database.IQueryRecordCount#setQueryRecordCount(long)
     */
	public void setQueryRecordCount(long queryRecordCount) {
		this.queryRecordCount = queryRecordCount;
	}

	public Object handle(ResultSet rs) throws SQLException {
		boolean initialized = false;
		ArrayList rows = new ArrayList();
		while (rs.next()) {
			if (needQueryCount && !returnByOutParameter && !initialized) {
				this.queryRecordCount = rs.getLong(IQueryRecordCount.COUNT_COLUMN_NAME);
				initialized = true;
			}
			rows.add(handleRow(rs));
		}
		return rows;
	}

	private static BasicRowProcessor rowProcessor = new BasicRowProcessor();
	/**
	 * 处理结果集当前行
	 */
	protected Object handleRow(ResultSet rs) throws SQLException {
		return rowProcessor.toMap(rs);
	}
}
